package models

import (
	"errors"
	"github.com/beego/beego/v2/client/orm"
	"time"
)

type WechatMenu struct {
	Id           int64
	DepartmentId int64
	MenuName     string
	ParentId     int64
	MenuType     int
	MenuContent  string
	Orderby      int64
	UpdatedAt    int64
	CreatedAt    int64
	Childs       []*WechatMenu `orm:"-"`
}

func WechatMenuTableName() string {
	return TableName("wechat_menus")
}
func (a *WechatMenu) TableName() string {
	return WechatMenuTableName()
}

//获取单条菜单
func (m *WechatMenu) Get(id int64, curuser BackendUser) *WechatMenu {
	orm.NewOrm().QueryTable(WechatMenuTableName()).Filter("DepartmentId", curuser.DepartmentId).Filter("id", id).One(m)
	return m
}

//保存菜单
func (m *WechatMenu) Save(curuser BackendUser) error {

	if m.Id == 0 {

		if m.ParentId == 0 {
			if err := m.checkParnetLen(curuser); err != nil { //验证主菜单
				return err
			}
		} else {
			if err := m.checkChildLen(m.ParentId, curuser); err != nil { //验证子菜单
				return err
			}
		}
		m.CreatedAt = time.Now().Unix()
		m.UpdatedAt = m.CreatedAt
		if _, err := orm.NewOrm().Insert(m); err != nil {
			return err
		}
	} else {
		m.UpdatedAt = time.Now().Unix()
		if _, err := orm.NewOrm().Update(m); err != nil {
			return err
		}
	}
	return nil
}

func (m *WechatMenu) checkParnetLen(curuser BackendUser) error {
	if count, _ := orm.NewOrm().QueryTable(WechatMenuTableName()).Filter("DepartmentId", curuser.DepartmentId).Filter("parent_id", 0).Count(); count >= 3 { //超出限制
		return errors.New("主菜单不能超过三条")
	}
	return nil
}
func (m *WechatMenu) checkChildLen(pid int64, curuser BackendUser) error {
	if count, _ := orm.NewOrm().QueryTable(WechatMenuTableName()).Filter("DepartmentId", curuser.DepartmentId).Filter("parent_id", pid).Count(); count >= 5 { //超出限制
		return errors.New("子菜单不能超过五条")
	}
	return nil
}

//获取所有菜单
func (m *WechatMenu) All(curuser BackendUser) []*WechatMenu {

	menus := make([]*WechatMenu, 0)
	if _, err := orm.NewOrm().QueryTable(WechatMenuTableName()).Filter("DepartmentId", curuser.DepartmentId).OrderBy("parent_id", "-orderby").Limit(20).All(&menus); err != nil {
		return nil
	}

	menusresult := make(map[int64]*WechatMenu)
	sort := make([]int64, 0)
	for k, _ := range menus {
		mu := menus[k]
		if mu.ParentId == 0 {
			menusresult[mu.Id] = mu
			sort = append(sort, mu.Id)
		} else {
			menusresult[mu.ParentId].Childs = append(menusresult[mu.ParentId].Childs, mu)
		}
	}
	result := make([]*WechatMenu, 0)
	for _, k := range sort {
		result = append(result, menusresult[k])
	}
	return result
}

//删除菜单
func (m *WechatMenu) Del(id int64, curuser BackendUser) error {
	orm := orm.NewOrm().QueryTable(WechatMenuTableName())
	//判断是否有下级
	if count, _ := orm.Filter("parent_id", id).Filter("DepartmentId", curuser.DepartmentId).Count(); count > 0 {
		return errors.New("请先删除下级菜单")
	}
	if _, err := orm.Filter("id", id).Filter("DepartmentId", curuser.DepartmentId).Delete(); err != nil {
		return err
	}
	return nil
}
